package com.joven.shelltest.utils;

import cn.hutool.core.util.URLUtil;
import cn.hutool.crypto.digest.MD5;
import org.apache.commons.lang3.StringUtils;

import java.security.SecureRandom;
import java.util.*;

/**
 * 签名生成工具
 * @Author wzj
 * @Date 2023-11-23 08:40
 **/
public class SignUtils {
    private static String getSign(Map<String, Object> map, String secretKey) {
        List<Map.Entry<String, Object>> infoIds = new ArrayList<>(map.entrySet());
        infoIds.sort(Map.Entry.comparingByKey());
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> m : infoIds) {
            if (null == m.getValue() || StringUtils.isNotBlank(m.getValue().toString())) {
                sb.append(m.getKey()).append("=").append(URLUtil.encodeAll(m.getValue().toString())).append("&");
            }
        }
        sb.append("secret-key=").append(secretKey);
        return MD5.create().digestHex(sb.toString()).toUpperCase();
    }

    public static boolean signValidate(Map<String, Object> map, String secretKey, String sign) {
        String mySign = getSign(map, secretKey);
        return mySign.equals(sign);
    }

    public static String getNonceStr(int length) {
        //生成随机字符串
        String str = "zxcvbnmlkjhgfdsaqwertyuiopQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
        Random random = new Random();
        StringBuilder randomStr = new StringBuilder();
        // 设置生成字符串的长度，用于循环
        for (int i = 0; i < length; ++i) {
            //从62个的数字或字母中选择
            int number = random.nextInt(62);
            //将产生的数字通过length次承载到sb中
            randomStr.append(str.charAt(number));
        }
        return randomStr.toString();
    }

    /** 指定生成的key长度为32字节 */
    private static final int KEY_LENGTH = 32;

    public static String generateAccessKey() {
        SecureRandom random = new SecureRandom();
        // 生成的字节数要除以2
        byte[] bytes = new byte[KEY_LENGTH / 2];
        random.nextBytes(bytes);
        return Base64.getEncoder().encodeToString(bytes).replace("/", "").replace("+", "").substring(0, 20);
    }

    public static String generateSecretKey() {
        SecureRandom random = new SecureRandom();
        byte[] bytes = new byte[KEY_LENGTH];
        random.nextBytes(bytes);
        return Base64.getEncoder().encodeToString(bytes).replace("/", "").replace("+", "").substring(0, 40);
    }
}
